package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class BookRelatedQueries {
    private PopulateBooks populateBooks;

    public BookRelatedQueries(PopulateBooks populateBooks) {
        this.populateBooks = populateBooks;
    }

    public void tellUserIfBookIsReserved() throws IOException {
        boolean availabilityStatus;
        availabilityStatus = populateBooks.getBookShelf().get(this.selectBookFromRepository()).isAvailable();
        if (availabilityStatus){
        System.out.println("Thank You! Your book has been reserved");
        }
        else
        {
         System.out.println("Sorry,We don't have the book yet");
        }
    }

    public int selectBookFromRepository() throws IOException {
        int indexOfSelectedBook = -1;
        System.out.println("Select a book from the list");
        System.out.println("Enter the book name");
        String bookName = this.getBookFromUser();
        for (PopulateBooks someBook : populateBooks.getBookShelf()) {
            if (someBook.getTitle().equals(bookName)) {
                indexOfSelectedBook = populateBooks.getBookShelf().indexOf(someBook);
            }
        }
        return indexOfSelectedBook;
    }

    public String getBookFromUser() throws IOException {
       try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String bookName = br.readLine();
        return bookName;
       }
       catch(IOException ex) {
       return null;
        }
    }
}
